package com.panasonic.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.panasonic.common.exception.CustomException;
import com.panasonic.web.domain.cms.CmsExam;
import com.panasonic.web.domain.cms.CmsExamExaminee;
import com.panasonic.web.domain.cms.CmsExamQuestion;
import com.panasonic.web.domain.cms.CmsExamScore;
import com.panasonic.web.mapper.CmsExamExamineeDao;
import com.panasonic.web.mapper.CmsExamMapper;
import com.panasonic.web.mapper.CmsExamQuestionMapper;
import com.panasonic.web.mapper.CmsExamScoreMapper;
import com.panasonic.web.service.ICmsExamService;
import com.panasonic.web.util.CmsSecurityUtils;
import com.panasonic.web.vo.CmsExamReviewParameter;
import com.panasonic.web.vo.CmsExamReviewVo;
import com.panasonic.common.utils.DateUtils;
import com.panasonic.common.utils.StringUtils;
import com.panasonic.web.vo.ExamineeInfo;
import com.panasonic.web.vo.ExamineeVo;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 考试信息Service业务层处理
 *
 * @author lwf
 * @date 2021-11-16
 */
@Service
public class CmsExamServiceImpl implements ICmsExamService {
    @Autowired
    private CmsExamMapper cmsExamMapper;
    @Autowired
    private CmsExamScoreMapper cmsExamScoreMapper;

    @Autowired
    private CmsExamQuestionMapper cmsExamQuestionMapper;


    @Autowired
    private CmsExamExamineeDao cmsExamExamineeDao;

    /**
     * 查询考试信息
     *
     * @param id 考试信息ID
     * @return 考试信息
     */
    @Override
    public CmsExam selectCmsExamById(Long id) {
        return cmsExamMapper.selectCmsExamById(id);
    }

    /**
     * 查询考试信息列表
     *
     * @param cmsExam 考试信息
     * @return 考试信息
     */
    @Override
    public List<CmsExam> selectCmsExamList(CmsExam cmsExam) {
        final List<CmsExam> cmsExams;
        cmsExam.setCreateTime(DateUtils.getNowDate());
        if (CmsSecurityUtils.getUserType() > 0) {
            cmsExam.setPanId(CmsSecurityUtils.getPanId());
            cmsExams = cmsExamMapper.selectCmsExamListByPanId(cmsExam);

            if (CollectionUtils.isNotEmpty(cmsExams)) {
                List<Long> ids = cmsExams.stream().map(s -> s.getId()).collect(Collectors.toList());
                List<CmsExamScore> scores = cmsExamScoreMapper.selectScoreByExamIds(ids, CmsSecurityUtils.getUserId());
                if (CollectionUtils.isNotEmpty(scores)) {
                    scores.stream().forEach(s -> {
                        Optional<CmsExam> first = cmsExams.stream().filter(e -> e.getId().equals(s.getExamId())).findFirst();
                        if (first.isPresent()) {
                            CmsExam cmsExam1 = first.get();
                            cmsExam1.setScore(s.getExamScore().intValue());
                            cmsExam1.setExamStatus(s.getExamStatus().intValue());
                        }
                    });
                }
            }
        } else {
            cmsExams = cmsExamMapper.selectCmsExamList(cmsExam);
        }
        return cmsExams;
    }

    /**
     * 新增考试信息
     *
     * @param cmsExam 考试信息
     * @return 结果
     */
    @Transactional
    @Override
    public Long insertCmsExam(CmsExam cmsExam) {

        cmsExam.sumTotalScore();
        cmsExam.setCreateBy(CmsSecurityUtils.getUsername());
        cmsExam.setCreateTime(DateUtils.getNowDate());
        int rows = cmsExamMapper.insertCmsExam(cmsExam);
        insertCmsExamQuestion(cmsExam);
        return cmsExam.getId();
    }

    /**
     * 修改考试信息
     *
     * @param cmsExam 考试信息
     * @return 结果
     */
    @Transactional
    @Override
    public int updateCmsExam(CmsExam cmsExam) {
        cmsExam.setUpdateTime(DateUtils.getNowDate());
        cmsExamQuestionMapper.deleteCmsExamQuestionByExamId(cmsExam.getId());
        insertCmsExamQuestion(cmsExam);
        return cmsExamMapper.updateCmsExam(cmsExam);
    }

    /**
     * 批量删除考试信息
     *
     * @param ids 需要删除的考试信息ID
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteCmsExamByIds(Long[] ids) {
        cmsExamMapper.deleteCmsExamQuestionByExamIds(ids);
        return cmsExamMapper.deleteCmsExamByIds(ids);
    }

    /**
     * 删除考试信息信息
     *
     * @param id 考试信息ID
     * @return 结果
     */
    @Override
    public int deleteCmsExamById(Long id) {
        cmsExamMapper.deleteCmsExamQuestionByExamId(id);
        return cmsExamMapper.deleteCmsExamById(id);
    }

    @Override
    public List<CmsExamReviewVo> getReviewList(CmsExamReviewParameter parameter) {
        return cmsExamScoreMapper.getReviewList(parameter);
    }

    @Transactional
    @Override
    public void saveExaminees(ExamineeVo examineeVo) {
        if (examineeVo.getExamId() == 0) {
            throw new CustomException("考试编号不能为空");
        }
        if (ArrayUtils.isEmpty(examineeVo.getPanIds())) {
            throw new CustomException("考生id不能为空");
        }

        Map<String, Object> columnMap = new HashMap<String, Object>();
        columnMap.put("exam_id", examineeVo.getExamId());
        cmsExamExamineeDao.deleteByMap(columnMap);
        Arrays.stream(examineeVo.getPanIds())
                .forEach(s -> {
                    CmsExamExaminee examExaminee = new CmsExamExaminee();
                    examExaminee.setExamId(examineeVo.getExamId());
                    examExaminee.setUserPanId(s);
                    examExaminee.setCreateTime(DateUtils.getNowDate());
                    examExaminee.setCreateBy(CmsSecurityUtils.getUsername());
                    cmsExamExamineeDao.insert(examExaminee);
                });
    }

    @Override
    public List<ExamineeInfo> getExaminees(long examId) {
        List<ExamineeInfo> cmsExamExaminees = cmsExamExamineeDao.selectExamineesByExamId(examId);
        return cmsExamExaminees;
    }


    /**
     * 新增试卷问题信息
     *
     * @param cmsExam 考试信息对象
     */
    public void insertCmsExamQuestion(CmsExam cmsExam) {
        List<CmsExamQuestion> cmsExamQuestionList = cmsExam.getCmsExamQuestionList();
        Long id = cmsExam.getId();
        if (StringUtils.isNotNull(cmsExamQuestionList)) {

            List<CmsExamQuestion> list = new ArrayList<CmsExamQuestion>();
            int sort = 10;
            int totalScore = 0;
            for (CmsExamQuestion cmsExamQuestion : cmsExamQuestionList) {
                setScoreToQuestion(cmsExam, cmsExamQuestion);
                cmsExamQuestion.setCreateBy(CmsSecurityUtils.getUsername());
                cmsExamQuestion.setCreateTime(DateUtils.getNowDate());
                cmsExamQuestion.setExamId(id);
                cmsExamQuestion.setSort(sort++);
                totalScore += cmsExamQuestion.getScore();
                list.add(cmsExamQuestion);
            }
            if (list.size() > 0) {
                cmsExamMapper.batchCmsExamQuestion(list);
                cmsExamMapper.updateCmsExam(cmsExam);
            }
        }
    }

    private void setScoreToQuestion(CmsExam cmsExam, CmsExamQuestion cmsExamQuestion) {
        int score = 0;
        switch (cmsExamQuestion.getType()) {
            case 0:
                score = cmsExam.getChooseScore();
                break;
            case 1:
                score = cmsExam.getFillInTheBlankScore();
                break;
            case 2:
                score = cmsExam.getOtherScore();
        }
        cmsExamQuestion.setScore(score);
    }


}
